<template>
  <div>
    <router-view>
      <div>
        <el-card class="box-card">
          <template #header>
            <div style="width: 100%; display: flex; justify-content: space-between">
              <div style="font-size: 20px; font-weight: 600">角色管理</div>
              <div style="width: 20%; display: flex; justify-content: flex-end">
                <el-button type="primary" @click="add">新建角色</el-button>
              </div>
            </div>
            <div style="height: 2vh"></div>
            <div style="display: flex; align-items: center">
              <div style="display: flex; align-items: center">
                <el-input v-model="input" placeholder="输入角色名称" clearable style="width: 250px" @input="docsearch" />
                <div style="width: 8px"></div>
                <el-select v-model="switdh" class="m-2" placeholder="请选择角色状态" clearable style="width: 250px"
                  @change="docsearch">
                  <el-option label="开启" value="1" />
                  <el-option label="关闭" value="2" />
                </el-select>
                <div style="width: 8px"></div>
              </div>
            </div>
          </template>
          <div style="width: 100%; height: auto; min-height: 60vh">
            <el-table ref="multipleTableRef" style="width: 100%" stripe
              :data="tableData.slice((currentPage4 - 1) * pageSize4, currentPage4 * pageSize4)" v-loading="loading"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="100" />
              <el-table-column label="序号" property="id" width="100" align="center" fixed />
              <el-table-column label="用户名称" property="name" align="center" fixed />
              <el-table-column property="status" label="是否开启" show-overflow-tooltip align="center">
                <template #default="{ row }">
                  <div :style="{ color: row.status == 1 ? '#A0CFFF' : '#cecece' }">
                    {{ row.status == 1 ? '·已开启' : '·已关闭' }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column property="create_time" label="添加时间" show-overflow-tooltip align="center" />
              <el-table-column fixed="right" label="操作" width="120" align="center">
                <template #default="scope">
                  <div style="width: 100%; display: flex; justify-content: space-around" v-if="scope.row.id != 1">
                    <el-button type="primary" plain size="small" @click="edit_cenyet(scope.row)">编辑</el-button>
                    <el-button type="danger" plain size="small" @click="delete_cenyet(scope.row)">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="display: flex; justify-content: center">
            <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
              :page-sizes="[10, 20, 50, 100]" :small="small" :disabled="disabled" :background="background"
              layout="total, sizes, prev, pager, next, jumper" :total="tableData.length" />
          </div>
        </el-card>
      </div>
      <el-dialog v-model="details" :title="text_up" top="3vh" width="50%" :before-close="handleClose">
        <!-- <template #footer> -->
        <el-form ref="ruleFormRefs" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
          :size="formSize" status-icon>
          <el-form-item label="用户名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="用户账号" prop="introduce">
            <el-input v-model="ruleForm.introduce" placeholder="请输入用户账号" />
          </el-form-item>
          <el-form-item label="是否开启 ">
            <div>
              <el-switch size="small" v-model="value1" />
            </div>
          </el-form-item>
          <el-form-item label="权限列表">
            <!-- 权限列表 -->
            <div class="deatiles">
              <div>
                <el-tree :data="child" show-checkbox node-key="id" :default-checked-keys="checked_id"
                  :props="defaultProps" @check="handleNodeClick" />
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div style="width: 100%; display: flex; justify-content: flex-end">
              <el-button @click="submitForm(ruleFormRefs)"> 取消 </el-button>
              <el-button type="primary" @click="ready(ruleFormRefs)">确认</el-button>
            </div>
          </el-form-item>
        </el-form>
        <!-- </template> -->
      </el-dialog>
    </router-view>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import { menu_list, role_list, add_edit, menu_del } from '@/api/prople';
import { Plus, Delete, Edit } from '@element-plus/icons-vue';
const menrList = ref([]);
const roleList = ref([]);
const multipleTableRef = ref();
const input = ref('');
const switdh = ref();
const tableData = ref([]);
const currentPage4 = ref(1);
const pageSize4 = ref(10);
const datesearch = ref([]);
const loading = ref(true);
const details = ref(false);
const name = ref();
const edit_item = ref();
const introduce = ref();
const text_up = ref('角色添加');
const child = ref([]);
const checked_id = ref([1]);
const value1 = ref(false);
const ruleFormRefs = ref();
const value_status = ref(false);
const formSize = ref('default');
const defaultProps = {
  children: 'children',
  label: 'label',
  disabled: 'disabled',
};
const ruleForm = ref({
  name: '',
  introduce: '',
});
const rules = reactive({
  name: [{ required: true, message: '请输入用户的名称', trigger: 'blur' }],
  introduce: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
});
menu();
function menu() {
  menu_list()
    .then((res) => {
      console.log(res);
      menrList.value = res.data;
      const aaa = processMenuItems(res.data);
      child.value = aaa;
    })
    .catch((err) => {
      console.log(err);
    });
}
// 角色列表
list();
function list() {
  role_list()
    .then((res) => {
      console.log(res);
      roleList.value = res.data;
      tableData.value = res.data;
      datesearch.value = res.data;
      loading.value = false;
    })
    .catch((err) => {
      console.log(err);
    });
}
// 搜索
function docsearch() {
  console.log(input.value);
  console.log(datesearch.value);
  const obj = {
    name: input.value,
    status: switdh.value,
  };
  const result = filter(obj, datesearch.value);
  console.log(result, 3333);
  tableData.value = result;
}

const filter = (condition, data) => {
  return data.filter((item) => {
    return Object.keys(condition).every((key) => {
      return String(item[key])
        .toLowerCase()
        .includes(String(condition[key]).trim().toLowerCase());
    });
  });
};

const edit_cenyet = (item) => {
  console.log(item);
  details.value = true;
  edit_item.value = item;
  ruleForm.value = {
    name: item.name,
    introduce: item.describe,
  };
  value1.value = item.status == 1 ? true : false;
  checked_id.value = item.menu_id.split(',');
  console.log(checked_id.value);
  value_status.value = false;
  text_up.value = '角色编辑';
};
// 添加
const add = () => {
  details.value = true;
  edit_item.value = true;
  value_status.value = true;
  ruleForm.value = {
    name: '',
    introduce: '',
  };
  name.value = '';
  introduce.value = '';
  value1.value = false;
  checked_id.value = [1];
  text_up.value = '角色添加';
};

// 树形处理
function processMenuItems(menuItems, pid = 0) {
  const processedItems = [];
  for (const item of menuItems) {
    if (item.pid === pid) {
      const processedItem = {
        id: item.id,
        label: item.name,
        path: item.path,
        icon: item.icon,
        disabled: item.id == 1 ? true : false,
        children: processMenuItems(menuItems, item.id),
      };
      processedItems.push(processedItem);
    }
  }
  return processedItems;
}
const handleNodeClick = (data, checked) => {
  console.log('chectedArray', data, checked);
  checked_id.value = checked.checkedKeys;
};

// 取消
const submitForm = (formEl) => {
  console.log(formEl);
  if (!formEl) return;
  formEl.clearValidate();
  details.value = false;
};

const ready = async (formEl) => {
  console.log(value1.value);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (value_status.value) {
        add_edit({
          name: ruleForm.value.name,
          describe: ruleForm.value.introduce,
          status: value1.value == true ? 1 : 2,
          menu_id: checked_id.value.join(','),
        })
          .then((res) => {
            console.log(res);
            list();
            details.value = false;
            ElMessage({
              message: '添加成功',
              type: 'success',
            });
          })
          .catch((err) => {
            console.log(err);
            ElMessage.error('添加失败');
          });
      } else {
        add_edit({
          name: ruleForm.value.name,
          describe: ruleForm.value.introduce,
          status: value1.value == true ? 1 : 2,
          menu_id: checked_id.value.join(','),
          id: edit_item.value.id,
        })
          .then((res) => {
            console.log(res);
            list();
            details.value = false;
            ElMessage({
              message: '编辑成功',
              type: 'success',
            });
          })
          .catch((err) => {
            console.log(err);
            // ElMessage.error('编辑失败');
          });
      }
    } else {
            console.log('error submit!', fields);
        }
    });
};
// 删除
const delete_cenyet = (item) => {
  console.log(item);
  ElMessageBox.confirm('你确定要删除该数据嘛？', '提示', {
    confirmButtonText: '确定删除',
    cancelButtonText: '我再想想',
    type: 'Warning',
  })
    .then(() => {
      menu_del({
        id: item.id,
      })
        .then((res) => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          });
          list();
          loading.value = true;
        })
        .catch((err) => {
          ElMessage({
            type: 'error',
            message: '删除失败',
          });
        });
    })
    .catch(() => { });
};
</script>
<style scoped></style>
